import numpy as np
import pandas as pd

from apps.api.mapper import sql_connect


# 统计年每天的温度、租聘的自行车数量、降雨量、能见度变化趋势 --> 四个图例的折线图数据
def deal_trend() -> dict:
    df = sql_connect.read_data_from_db()

    # 设置时间索引列
    df['Date'] = pd.to_datetime(df['Date'], format='%Y/%m/%d')
    df.set_index('Date', inplace=True)

    # 聚合
    daily_stats = df.resample('D').agg(
        {'Temperature': 'mean', 'RentedBikeCount': 'sum', 'Rainfall': 'sum', 'Visibility': 'mean'})
    daily_stats = daily_stats.dropna().head(100)
    time_list = daily_stats.index.strftime('%Y/%m/%d')

    # 将datetime对象转换为字符串
    time_list = time_list.tolist()

    response = {
        'temperature_list': np.round(daily_stats['Temperature'].tolist(), 2).tolist(),
        'RentedBikeCount': np.round(daily_stats['RentedBikeCount'].tolist(), 2).tolist(),
        'Rainfall': np.round(daily_stats['Rainfall'].tolist(), 2).tolist(),
        'Visibility': np.round(daily_stats['Visibility'].tolist(), 2).tolist(),
        'time': time_list
    }
    return response


# 基本信息模块：平均能见度、平均温度、平均湿度、平均风速、平均太阳辐射、平均降雨量、总记录、节假日占比
def deal_general() -> dict:
    data = sql_connect.read_data_from_db()
    # 平均能见度
    aver_vis = np.round(data['Visibility'].mean(), 2)
    # 平均温度
    aver_temp = np.round(data['Temperature'].mean(), 2)
    # 平均湿度
    aver_humid = np.round(data['Humidity'].mean(), 2)
    # 平均风速
    aver_wind_speed = np.round(data['WindSpeed'].mean(), 2)
    # 平均太阳辐射
    aver_radiation = np.round(data['SolarRadiation'].mean(), 2)
    # 平均降雨量
    aver_rainfall = np.round(data['Rainfall'].mean(), 2)
    # 总记录数
    total_num = len(data['SolarRadiation'].tolist())

    # 节假日占比
    holiday_count = len(data[data['Holiday'] == 'Holiday']['Holiday'].tolist())
    holiday_percentage = (holiday_count / total_num) * 100

    # 大降雨量占比
    over_rain = len(data[data['Rainfall'] >= aver_rainfall]['Rainfall'].tolist()) / total_num * 100

    # 强风占比
    over_wind = len(data[data['WindSpeed'] >= aver_wind_speed]['WindSpeed'].tolist()) / total_num * 100
    # 时间跨度
    data['Date'] = pd.to_datetime(data['Date'])
    time_span_years = (data['Date'].max() - data['Date'].min()).days / 365

    # 夏天记录数
    summer_count = len(data[data['Seasons'] == "Summer"]['Seasons'])

    # 冬天记录数
    winter_count = len(data[data['Seasons'] == "Winter"]['Seasons'])

    response = {
        'aver_vis': aver_vis,
        'aver_temp': aver_temp,
        'aver_humid': aver_humid,
        'aver_wind_speed': aver_wind_speed,
        'aver_radiation': aver_radiation,
        'aver_rainfall': aver_rainfall,
        'total_num': total_num,
        'holiday_percentage': np.round(holiday_percentage, 0),
        'over_rain': np.round(over_rain, 0),
        'over_wind': np.round(over_wind, 0),
        'time_span_years': np.round(time_span_years, 1),
        'summer_count': summer_count,
        'winter_count': winter_count,

    }
    return response


# 统计不同月份下的骑行人数、平均能见度、总降雨量、总辐射量
def deal_rank_ride() -> dict:
    data = sql_connect.read_data_from_db()
    data['Date'] = pd.to_datetime(data['Date'])

    # 不同月份下的骑行人数
    monthly_ridership = data.groupby(data['Date'].dt.month)['RentedBikeCount'].sum().sort_values(ascending=False)
    # 平均能见度
    aver_vis_month = data.groupby(data['Date'].dt.month)['Visibility'].mean()
    # 总降雨量
    aver_rain_month = data.groupby(data['Date'].dt.month)['Rainfall'].sum()
    # 总辐射量
    aver_rad_month = data.groupby(data['Date'].dt.month)['SolarRadiation'].sum()
    # 月份
    month_list = monthly_ridership.index.tolist()

    # 夏天的骑行人数
    summer_riders = data[data['Seasons'] == "Summer"]['RentedBikeCount'].sum()
    # 春季骑行人数
    spring_riders = data[data['Seasons'] == "Spring"]['RentedBikeCount'].sum()
    # 秋季骑行人数
    autumn_riders = data[data['Seasons'] == "Autumn"]['RentedBikeCount'].sum()

    response = {
        'monthly_ridership': list(monthly_ridership.values),
        'month_list': month_list,
        'aver_vis_month': list(aver_vis_month.values),
        'aver_rain_month': list(aver_rain_month.values),
        'aver_rad_month': list(aver_rad_month.values),
        'summer_riders': summer_riders,
        'spring_riders': spring_riders,
        'autumn_riders': autumn_riders,
    }
    return response


deal_rank_ride()
